# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from dnsmanager.dnsadmin.models import User, Zone
import re
import md5
import datetime


def check_auth(request):
    if not request.session.get('user_id'):
        t = loader.get_template('no_auth.html')
        return HttpResponse(t.render(Context(dict())))

        
def zone_add(request):
    check_auth(request)
    errors = []
    
    if "name" in request.POST:
        name = request.POST["name"]
    else:
        name = ""
    if "lookup" in request.POST:
        lookup = request.POST["lookup"]
        if not lookup in ["1", "2"]:
            lookup = "1"
    else:
        lookup = "1"
    if "serial_number" in request.POST:
        serial_number = request.POST["serial_number"]
    else:
        serial_number = ""
    #refresh time
    if "refresh_time" in request.POST:
        refresh_time = request.POST["refresh_time"]
    else:
        refresh_time = ""
    #retry time
    if "retry_time" in request.POST:
        retry_time = request.POST["retry_time"]
    else:
        retry_time = ""
    #expire time
    if "expire_time" in request.POST:
        expire_time = request.POST["expire_time"]
    else:
        expire_time = ""
    #minimum ttl
    if "minimum_ttl" in request.POST:
        minimum_ttl = request.POST["minimum_ttl"]
    else:
        minimum_ttl = ""
    #source host
    if "source_host" in request.POST:
        source_host = request.POST["source_host"]
    else:
        source_host = ""
    #contact email
    if "contact_email" in request.POST:
        contact_email = request.POST["contact_email"]
    else:
        contact_email = ""
    #enabled
    if "enabled" in request.POST:
        enabled = True
    else:
        enabled = False

    if name and not errors:
        zone_new = Zone()
        if lookup == "1":
            forward_lookup = True
        else: 
            forward_lookup = False
        zone_new.forward_lookup = forward_lookup
        zone_new.name = name
        zone_new.serial_number = serial_number
        zone_new.refresh_time = refresh_time
        zone_new.retry_time = retry_time
        zone_new.expire_time = expire_time
        zone_new.minimum_ttl = minimum_ttl
        zone_new.source_host = source_host
        zone_new.contact_email = contact_email
        zone_new.creation =  datetime.datetime.now()
        zone_new.enabled = enabled
        zone_new.save()
    
    t = loader.get_template('zone_add.html')
    c = Context({
        "name": name,
        "lookup": lookup,
        "serial_number": serial_number,
        "refresh_time": refresh_time,
        "retry_time": retry_time,
        "expire_time": expire_time,
        "minimum_ttl": minimum_ttl,
        "source_host": source_host,
        "contact_email": contact_email,
        "enabled": enabled,
        "errors": errors
    })
    return HttpResponse(t.render(c))

def zone_list(request):
    check_auth(request)
    t = loader.get_template('zone_list.html')
    c = Context({
        "zone_list": Zone.objects.all()
    })
    return HttpResponse(t.render(c))

def auth_page(request):
    errors = []
    if "name" in request.POST:
        name = request.POST["name"]
        name = name.strip()
        if "password" in request.POST:
            password = request.POST["password"]
        else:
            password = ""
            
        user = User.objects.filter(name=name, password=md5.md5(password).hexdigest())
        if user:
            request.session['user_id'] = user[0].id
            return HttpResponseRedirect("/zone-list")
        else:
            errors.append(u"Имя / Пароль неверны")
    else:
        name = ""
        
    t = loader.get_template('auth_page.html')
    c = Context({
        "name": name,
        "errors": errors
    })
    return HttpResponse(t.render(c))

def registration_page(request):
    errors = []
    if "name" in request.POST:
        name = request.POST["name"]
        if name == "":        
            errors.append(u"Введите имя")
        else:
            name = name.strip()
            if len(name) < 4:
                errors.append(u"Имя долно быть не менее 5 символов")
            elif len(name) > 50:
                errors.append(u"Имя долно быть не более 50 символов")
            if not re.search(r"^[a-zA-Z0-9]*$", name):
                errors.append(u"Имя может содержать только цифры и буквы английского алфавита")
            if User.objects.filter(name=name):
                errors.append(u"Пользователь с таким именем уже зарегистрирован")
    else:
        name = ""

    password_repeat = ""
    if "password" in request.POST:
        password = request.POST["password"]
        if password == "":
            errors.append(u"Введите пароль")
        elif len(password) < 6:
            errors.append(u"Пароль должен быть не менее 6 символов")
        else:
            if "password_repeat" in request.POST:
                password_repeat = request.POST["password_repeat"]
            if password_repeat != password:
                errors.append(u"Пароль и повтор пароля не совпадают")
    else:
        password = ""

    if name and password and not errors:
        user_new = User()
        user_new.name = name
        user_new.password =  md5.md5(password).hexdigest()
        user_new.enabled = False
        user_new.creation = datetime.datetime.now()
        user_new.save()
        t = loader.get_template('registration_success.html')
        c = Context({
            "name": name
        })
        return HttpResponse(t.render(c))
        
    c = Context({
        "name": name,
        "password": password,
        "password_repeat": password_repeat,
        "errors": errors
    })
    t = loader.get_template('registration_page.html')
    return HttpResponse(t.render(c))

def error404(request, path):
    t = loader.get_template('error404.html')
    c = Context({
        "path": path,
    })
    return HttpResponse(t.render(c))
